<?php

namespace XWAM\Model;

/**
 * CustomerModel类
 *
 * @since VER:1.0; DATE:2016-1-22; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class CustomerModel extends AppbaseModel {

    protected $tableName = 't_porg_customer';

    /**
     * 分页查询
     * @param string $pager
     * @param array $afields
     * @param integer $site_id
     * @param array $asearch
     * @return array
     * @since 1.0 2016-5-11 SoChishun Added.
     */
    function paging_select(&$pager, &$afields, $site_id, $asearch) {
        $m_attr = new CustomerAttrModel();
        $afields = $m_attr->get_customer_list_fields($site_id, array('id' => '', 'serial_no' => '客户ID', 'name' => '姓名', 'telphone' => '电话', 'sex' => '性别', 'address' => '地址', 'user_name' => '工号'));
        if ($afields['custom']) {
            $table = $this->tableName . ' c left join ' . $this->tableName . '_s' . $site_id . ' s on c.id=s.customer_id';
            $field = implode(',c.', array_keys($afields['system'])) . implode(',s.', array_keys($afields['custom']));
        } else {
            $table = $this->tableName;
            $field = array_keys($afields['system']);
        }
        return $this->get_paging_list($pager, array('table' => $table, 'field' => $field, 'where' => $asearch['where'], 'order' => 'id desc'), array('page_params' => $asearch['search']));
    }

    /**
     * 导出查询
     * @param type $site_id
     * @param type $asearch
     * @return type
     * @since 1.0 2016-5-12 SoChishun Added.
     */
    function export_select($site_id, $asearch) {
        $m_attr = new CustomerAttrModel();
        $afields = $m_attr->get_customer_export_fields($site_id, array('name' => '姓名', 'telphone' => '电话', 'sex' => '性别', 'address' => '地址'));
        if ($afields['custom']) {
            $table = $this->tableName . ' c left join ' . $this->tableName . '_s' . $site_id . ' s on c.id=s.customer_id';
            $afield = array();
            foreach ($afields['system'] as $field => $text) {
                $afield[] = "c.$field as '$text'";
            }
            foreach ($afields['custom'] as $field => $text) {
                $afield[] = "s.$field as '$text'";
            }
        } else {
            $table = $this->tableName;
            $afield = $afields['system'];
        }
        return $this->table($table)->field($afield)->where($asearch['where'])->select();
    }

    /**
     * 获取客户
     * <br />自动生成的只有两个字段
     * @param mixed $where
     * @return boolean
     * @since VER:1.0; DATE:2016-1-22; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
     */
    function find_customer($where) {
        $cache_key = 'find_customer_' . md5(serialize($where));
        $cache_data = S($cache_key);
        if ($cache_data) {
            return $cache_data;
        }

        $data = false;
        if ($where) {
            $data = $this->where($where)->find();
        }
        if ($data) {
            $this->where($where)->setField('review_time', date('Y-m-d h:i:s')); // 更新最后联系时间
        }
        S($cache_key, $data, 15);
        return $data;
    }

    /**
     * 从xcall导入号码表读取
     * @param type $exten
     * @param type $tel
     * @since 1.0 2016-4-18 SoChishun Added.
     */
    function find_customer_from_xcall($exten, $tel) {
        $cache_name = 'exten_tsids_' . $exten;
        $atsids = S($cache_name);
        if (!$atsids) {
            $result = $this->query('select s.id from db_xcall.tcti_task_strategy s inner join db_xcall.tuser_member u on s.siteID=u.siteID where u.extensionNumber=' . $exten);
            $atsids = array();
            foreach ($result as $arr) {
                $atsids[] = $arr['id'];
            }
            S($cache_name, $atsids, 15);
        }
        $data = false;
        if ($atsids) {
            $tmpdata = array();
            foreach ($atsids as $tsid) {
                $list = $this->query("select customerName as name, phoneNumber as telphone, sex, address, detailMsg as remark from db_xcall.tcti_call_number$tsid where phoneNumber like '%$tel' and customerName <> '' limit 1");
                if ($list) {
                    $data = $list[0];
                    break;
                }
            }
        }
        return $data;
    }

    // 保存客户 2016-1-22
    function save_customer() {
        $rules = array(
            array('serial_no', 'require', '客户编号无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('serial_no', 'require', '客户编号冲突!', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT),
            array('name', 'require', '客户姓名无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('telphone', 'require', '联系电话无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        //图片上传
        //$msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Customer/', 'skipEmpty' => true));
        //if (is_array($msg) && isset($msg['face_url'])) {
        //    $this->data['face_url'] = $msg['face_url']['filepath'];
        //}
        $address_data = array(
            'name' => $this->data['name'],
            'telphone' => $this->data['telphone'],
            'address' => isset($this->data['address']) ? $this->data['address'] : '',
            'zip' => isset($this->data['zip']) ? $this->data['zip'] : '',
        );
        // 拆分数据
        $site_id = $this->site_id;
        $m_attr = new CustomerAttrModel();
        $afields = $m_attr->where(array('site_id' => $site_id))->getField('field_name, field_type, is_system');
        $data_custom = array();
        if (is_array($afields)) {
            $anotnull = array('int', 'decimal', 'datetime', 'date', 'time');
            $data = $this->data;
            foreach ($afields as $field => $row) {
                if (in_array($row['field_type'], $anotnull) && empty($data[$field])) {
                    unset($data[$field]); // 去掉空值
                    continue;
                }
                if ('N' == $row['is_system']) {
                    $data_custom[$field] = $data[$field];
                    unset($data[$field]);
                    continue;
                }
            }
            $this->data = $data;
        }
        // 保存到主表
        $id = false;
        $this->review_time = date('Y-m-d H:i:s'); // 最后沟通时间
        if (empty($this->id)) {
            $this->status = 1;
            $this->is_shared = 'N'; // 是否共享
            unset($this->data['id']);
            $result = $this->add();
            $id = $result;
        } else {
            $id = $this->id;
            unset($this->data['user_name']);
            unset($this->data['site_id']);
            $result = $this->save();
        }
        if (false === $result) {
            return $this->returnMsg(false, $this->getDbError());
        }
        // 保存到扩展表
        if (is_array($afields_custom) && false !== $result && $id) {
            $table = 't_porg_customer_s' . $site_id;
            if (empty($this->id)) {
                $this->table($table)->save($data_custom);
            } else {
                $data_custom['customer_id'] = $id;
                $this->table($table)->add($data_custom);
            }
        }
        // 其他解析操作
        if (false !== $result && $id) {
            if (!empty($this->data['labels'])) {
                // 保存标签
                $m_tag = new CustomerTagModel();
                $m_tag->add_tag($this->labels);
            }
            // 保存地址
            $m_addr = new CustomerAddressModel();
            $m_addr->add_customer_address($address_data, $id);
        }
        return $this->returnMsg($result);
    }

    // 物理删除客户
    function delete_customer($id) {
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    // 逻辑删除客户
    function recycle_customer($id) {
        $result = $this->where(array('id' => array('in', $id)))->setField('status', 4);
        return $this->returnMsg($result);
    }

    // 逻辑恢复客户
    function restore_customer($id) {
        $result = $this->where(array('id' => array('in', $id)))->setField('status', 1);
        return $this->returnMsg($result);
    }

    // 共享客户
    function share_customer($id) {
        $result = $this->where(array('id' => array('in', $id)))->setField('is_shared', 'Y');
        return $this->returnMsg($result);
    }

}
